import requests
from requests.auth import HTTPDigestAuth
from setting import logger
import datetime
from util import parse_ascII_to_command

class Ns:

    def __init__(self, host) -> None:

        self.host = host

        self.session = requests.Session()

        self.login()


    def login(self): # 发送带有Digest身份验证头部的请求进行登录

        username = 'admin'
        password = 'admin'

        self.session.auth = HTTPDigestAuth(username, password)
        # 发送带有Digest身份验证头部的请求进行登录
        response = self.session.get(f"http://{self.host}")

        # 检查登录是否成功
        if response.status_code == 200:

            logger.info('登录成功！')

        else:

            logger.error('登录失败！')

            raise

    def get_all_nodes(self):

        url = f"http://{self.host}/api/nodes?_page=1&_perPage=300&_sortDir=DESC&_sortField=health_decay"

        r = self.session.get(url)

        return r.json()
    
    def set_nodes(self, nodes_addr: str, up_data: dict): # 节点更新数据

        url = f"http://{self.host}/api/nodes/{nodes_addr}"

        data = self.session.get(url).json()

        data.update(up_data)

        self.session.put(url, json=data)

        logger.info('节点更新成功')

    def set_nodes_all(self, up_data: dict): # 所有节点更新数据

        for i in self.get_all_nodes():

            url = f"http://{self.host}/api/nodes/{i['devaddr']}"

            i.update(up_data)

            self.session.put(url, json=i)

            logger.info(f"节点：{i['devaddr']}--更新成功：{up_data}")

    def reset_fcnt(self, devaddr: str): # 重置指定节点fcnt值

        r = self.session.get(f"http://{self.host}/api/nodes/{devaddr}")

        data = r.json()

        up_data = {'fcntup':0, 'fcntdown': 0}

        data.update(up_data)

        self.session.put(f"http://{self.host}/api/nodes/{devaddr}", json=data)

        logger.info(f"节点：{devaddr}--更新成功：{up_data}")


    def get_rxframes_list(self): # 获取Frames列表

        url = f"http://{self.host}/api/rxframes?_page=1&_perPage=3000&_sortDir=DESC&_sortField=datetime"

        r = self.session.get(url)

        return r.json()
    

    def get_rxframes_list_up(self): # 获取Frames列表

        url = f'http://{self.host}/api/rxframes'+'?_filters={"dir":"up"}&_page=1&_perPage=3000&_sortDir=DESC&_sortField=datetime'

        r = self.session.get(url)

        return r.json()
    
    def get_rxframes_list_by_devaddr(self, devaddr): # 获取Frames列表

        _devaddr = '{"devaddr":"' + devaddr + '","dir":"up"}'
 
        url = f'http://{self.host}/api/rxframes?_filters={_devaddr}&_page=1&_perPage=30&_sortDir=DESC&_sortField=datetime'

        print(url)

        r = self.session.get(url)

        return r.json()

    def get_downlinks(self, devaddr): # 获取节点当时队列

        url = f"http://{self.host}/api/queued?_filters=%7B%22devaddr%22:%22{devaddr}%22%7D&_page=1&_perPage=100"

        r = self.session.get(url)

        return r.json()
    

    def get_event(self): # 获取event事件列表

        url = f"http://{self.host}/api/events?_page=1&_perPage=30&_sortDir=DESC&_sortField=last_rx"

        r = self.session.get(url)

        return r.json()
    
    def get_connector_info(self): # 获取connector mqtt info

        '''{'app': 'LoRaWAN_001_Test', 'connid': 'ConnMasterMqtt', 'enabled': True, 'failed': [], 'format': 'json', 
        'health_alerts': [], 'health_decay': 0, 'health_reported': 0, 'publish_qos': 0, 
        'publish_uplinks': 'base_station_publish_channel', 'received': 'lora', 'subscribe': '1671CFFFFE8E831B', 
        'uri': 'mqtt://192.168.31.201:1883'}'''

        url = f"http://{self.host}/api/connectors/ConnMasterMqtt"

        r = self.session.get(url)

        return r.json()
    
    def set_connector_info(self, data): # 设置connector mqtt 
        '''{'app': 'LoRaWAN_001_Test', 'connid': 'ConnMasterMqtt', 'enabled': True, 'failed': [], 'format': 'json', 
        'health_alerts': [], 'health_decay': 0, 'health_reported': 0, 'publish_qos': 0, 
        'publish_uplinks': 'base_station_publish_channel', 'received': 'lora', 'subscribe': '1671CFFFFE8E831B', 
        'uri': 'mqtt://192.168.31.201:1883'}'''

        url = f"http://{self.host}/api/connectors/ConnMasterMqtt"

        self.session.put(url, json=data)

        logger.info(f"ConnMasterMqtt 重置成功")

    def restore_connector(self): # 恢复connector

        '''{'app': 'LoRaWAN_001_Test', 'connid': 'ConnMasterMqtt', 'enabled': True, 'failed': ['network'], 'format': 'json', 'health_alerts': ['failed'], 'health_decay': 100, 'health_reported': 100, 'publish_qos': 0, 'publish_uplinks': 
'base_station_publish_channel', 'received': 'lora', 'subscribe': '1671CFFFFE8E831B', 'uri': 'mqtt://192.168.31.201:1883'}'''
        
        data = self.get_connector_info()

        if data.get("failed") == []:

            return
        
        data["failed"] = []
        data["health_alerts"] = []
        data["health_decay"] = 0
        data["health_reported"] = 0

        url = f"http://{self.host}/api/connectors/ConnMasterMqtt"

        self.session.put(url, json=data)

        logger.info(f"ConnMasterMqtt 重置成功")

    
    def set_connector_mqtt_host(self, host): # 设置connector mqtt host

        '''{'app': 'LoRaWAN_001_Test', 'connid': 'ConnMasterMqtt', 'enabled': True, 'failed': ['network'], 'format': 'json', 'health_alerts': ['failed'], 'health_decay': 100, 'health_reported': 100, 'publish_qos': 0, 'publish_uplinks': 
'base_station_publish_channel', 'received': 'lora', 'subscribe': '1671CFFFFE8E831B', 'uri': 'mqtt://192.168.31.201:1883'}'''
        
        data = self.get_connector_info()
        data["failed"] = []
        data["health_alerts"] = []
        data["health_decay"] = 0
        data["health_reported"] = 0
        data["uri"] = f'mqtt://{host}:1883'

        url = f"http://{self.host}/api/connectors/ConnMasterMqtt"

        self.session.put(url, json=data)

        logger.info(f"ConnMasterMqtt 重置成功")

    def rxf_data_change_push_data(self, data):
        '''rxframes 数据格式转换成提交格式'''
        data["datr"] = data["gateways"][0]["rxq"]["datr"]
        data['codr'] = data["gateways"][0]["rxq"]["codr"]
        data["freq"] = data["gateways"][0]["rxq"]["freq"]
        data["lsnr"] = data["gateways"][0]["rxq"]["lsnr"]
        data["rssi"] = data["gateways"][0]["rxq"]["rssi"]
        data["text"] = parse_ascII_to_command(data["data"]).decode()

        del data["gateways"]

        return data

    def get_rxframes_list_by_timestamp(self, timestamp): # 获取Frames列表

        '''获取比timestamp大的rxframes, 并洗成上传格式
        {'codr': '4/5', 'data': '303545333039303031333030303037353937', 'datetime': '2023-11-01T00:16:49Z', 'datr': 'SF10BW125', 'devaddr': '9CDBF976', 'fcnt': 211, 'freq': 472.3, 'lsnr': 9.2, 'port': 12, 'rssi': -14, 'text': '05E309001300007597'}
        '''

        result = []

        rxframes_list = self.get_rxframes_list_up()

        for i in rxframes_list:

            # 字符串表示的日期时间
            dt_str = i["datetime"]

            # 将字符串转换为日期时间对象
            dt = datetime.datetime.strptime(dt_str, '%Y-%m-%dT%H:%M:%S.%fZ')

            # 将日期时间对象转换为时间戳
            i_timestamp = int(dt.timestamp())

            if i_timestamp > timestamp:

                result.append(self.rxf_data_change_push_data(i))

        return result

if __name__ == "__main__":

    n = Ns(host="192.168.31.101:8080")

    # n.set_nodes_all({"fcntup":0, "fcntdown": 0}) 

    # print(n.get_rxframes_list_by_devaddr("92B18DA6")[0])
    print(n.get_rxframes_list_by_timestamp(1698772748))